package com.googlecode.afdbaccess.web.common.servletfilter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class CharsetHeaderFilter implements Filter {
    //private final static Logger log = Logger.getLogger(CharsetHeaderFilter.class);
    
    private String charset = "iso-8859-1";
    
    class ResponseWrapper extends HttpServletResponseWrapper {
        public ResponseWrapper(HttpServletResponse response) {
            super(response);
        }

        @Override
        public void setCharacterEncoding(String wantedCharset) {
            // do nothing. Swallow the setting
            return;
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)res;
        //log.debug("before doFilter uri:" + ((HttpServletRequest)req).getRequestURI());
        response.setCharacterEncoding(charset);
        chain.doFilter(req, new ResponseWrapper(response));
        //log.debug("after doFilter uri:" + ((HttpServletRequest)req).getRequestURI());
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String charsetParam = filterConfig.getInitParameter("charset");
        if(charsetParam != null) {
            this.charset = charsetParam;
        }
    }

    @Override
    public void destroy() {
        // do nothing
    }
}